// DOM元素引用
const uploadArea = document.getElementById('uploadArea');
const fileUpload = document.getElementById('fileUpload');
const fileInfo = document.getElementById('fileInfo');
const fileName = document.getElementById('fileName');
const rowCount = document.getElementById('rowCount');
const columnCount = document.getElementById('columnCount');
const changeFile = document.getElementById('changeFile');
const promptInput = document.getElementById('promptInput');
const analyzeBtn = document.getElementById('analyzeBtn');
const resultCard = document.getElementById('resultCard');
const analysisLoading = document.getElementById('analysisLoading');
const analysisResult = document.getElementById('analysisResult');
const downloadBtn = document.getElementById('downloadBtn');
const reportsList = document.getElementById('reportsList');
const reportSearch = document.getElementById('reportSearch');
const reportFilter = document.getElementById('reportFilter');
const notification = document.getElementById('notification');
const notificationMessage = document.getElementById('notificationMessage');

// 导航切换
const navLinks = document.querySelectorAll('.nav-link');
const sections = document.querySelectorAll('.section');

navLinks.forEach(link => {
    link.addEventListener('click', (e) => {
        e.preventDefault();
        const targetSection = link.getAttribute('data-section');
        
        // 更新导航状态
        navLinks.forEach(l => l.classList.remove('active'));
        link.classList.add('active');
        
        // 显示目标部分
        sections.forEach(section => {
            if (section.id === targetSection) {
                section.classList.add('active');
                section.style.display = 'block';
            } else {
                section.classList.remove('active');
                section.style.display = 'none';
            }
        });
        
        // 如果切换到报告列表，加载报告
        if (targetSection === 'reports') {
            loadReports();
        }
    });
});

// 文件上传处理
let currentFileId = null;

uploadArea.addEventListener('click', () => {
    fileUpload.click();
});

uploadArea.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadArea.classList.add('active');
});

uploadArea.addEventListener('dragleave', () => {
    uploadArea.classList.remove('active');
});

uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.classList.remove('active');
    
    if (e.dataTransfer.files.length) {
        handleFileUpload(e.dataTransfer.files[0]);
    }
});

fileUpload.addEventListener('change', () => {
    if (fileUpload.files.length) {
        handleFileUpload(fileUpload.files[0]);
    }
});

changeFile.addEventListener('click', () => {
    fileInfo.style.display = 'none';
    uploadArea.style.display = 'block';
    currentFileId = null;
});

async function handleFileUpload(file) {
    if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
        showNotification('请上传Excel文件(.xlsx或.xls格式)');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', file);
    
    try {
        const response = await fetch('/api/upload', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (response.ok) {
            // 显示文件信息
            fileName.textContent = data.filename;
            rowCount.textContent = data.rows;
            columnCount.textContent = data.columns;
            
            uploadArea.style.display = 'none';
            fileInfo.style.display = 'block';
            
            currentFileId = data.file_id;
            showNotification('文件上传成功！');
        } else {
            showNotification(`上传失败: ${data.detail}`);
        }
    } catch (error) {
        console.error('上传错误:', error);
        showNotification('上传过程中发生错误，请重试');
    }
}

// 示例提示点击处理
const exampleBtns = document.querySelectorAll('.example-btn');
exampleBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        promptInput.value = btn.textContent;
    });
});

// 分析处理
let currentReportId = null;

analyzeBtn.addEventListener('click', async () => {
    const prompt = promptInput.value.trim();
    
    if (!prompt) {
        showNotification('请输入分析指令');
        return;
    }
    
    // 显示结果卡片和加载动画
    resultCard.style.display = 'block';
    analysisLoading.style.display = 'flex';
    analysisResult.style.display = 'none';
    document.querySelector('.result-actions').style.display = 'none';
    
    try {
        const response = await fetch('/api/analyze', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                prompt: prompt,
                excel_id: currentFileId
            })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            currentReportId = data.report_id;
            // 开始轮询结果
            pollAnalysisResult(data.report_id);
        } else {
            showAnalysisError(`分析请求失败: ${data.detail}`);
        }
    } catch (error) {
        console.error('分析错误:', error);
        showAnalysisError('发送分析请求时发生错误');
    }
});

async function pollAnalysisResult(reportId) {
    try {
        const response = await fetch(`/api/reports/${reportId}`);
        const data = await response.json();
        
        if (response.ok) {
            if (data.status === 'completed') {
                // 显示分析结果
                showAnalysisResult(data.result.analysis);
            } else if (data.status === 'failed') {
                showAnalysisError(data.error || '分析过程中发生错误');
            } else {
                // 继续轮询
                setTimeout(() => pollAnalysisResult(reportId), 2000);
            }
        } else {
            showAnalysisError(`获取分析结果失败: ${data.detail}`);
        }
    } catch (error) {
        console.error('轮询错误:', error);
        showAnalysisError('获取分析结果时发生错误');
    }
}

function showAnalysisResult(result) {
    analysisLoading.style.display = 'none';
    analysisResult.style.display = 'block';
    document.querySelector('.result-actions').style.display = 'flex';
    
    // 将Markdown格式的结果转换为HTML（简单实现，实际项目可使用专门的Markdown解析库）
    const formattedResult = result
        .replace(/\n\n/g, '<br><br>')
        .replace(/\n/g, '<br>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/#{3}\s(.*?)\n/g, '<h3>$1</h3>')
        .replace(/#{2}\s(.*?)\n/g, '<h2>$1</h2>')
        .replace(/#{1}\s(.*?)\n/g, '<h1>$1</h1>');
    
    analysisResult.innerHTML = formattedResult;
}

function showAnalysisError(error) {
    analysisLoading.style.display = 'none';
    analysisResult.style.display = 'block';
    analysisResult.innerHTML = `<div class="error-message"><i class="fas fa-exclamation-circle"></i> ${error}</div>`;
}

// 下载报告
downloadBtn.addEventListener('click', () => {
    if (currentReportId) {
        window.location.href = `/api/reports/${currentReportId}/download`;
    }
});

// 加载报告列表
async function loadReports() {
    try {
        const response = await fetch('/api/reports');
        const data = await response.json();
        
        if (response.ok) {
            renderReportsList(data);
        } else {
            reportsList.innerHTML = '<div class="empty-state"><i class="fas fa-exclamation-circle"></i><p>加载报告失败</p></div>';
        }
    } catch (error) {
        console.error('加载报告错误:', error);
        reportsList.innerHTML = '<div class="empty-state"><i class="fas fa-exclamation-circle"></i><p>加载报告时发生错误</p></div>';
    }
}

function renderReportsList(reports) {
    if (!reports.length) {
        reportsList.innerHTML = '<div class="empty-state"><i class="fas fa-folder-open"></i><p>暂无报告记录</p></div>';
        return;
    }
    
    const searchTerm = reportSearch.value.toLowerCase();
    const filterValue = reportFilter.value;
    
    const filteredReports = reports
        .filter(report => {
            const matchesSearch = report.filename.toLowerCase().includes(searchTerm) || 
                                (report.prompt && report.prompt.toLowerCase().includes(searchTerm));
            const matchesFilter = filterValue === 'all' || report.status === filterValue;
            return matchesSearch && matchesFilter;
        })
        .sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
    
    if (!filteredReports.length) {
        reportsList.innerHTML = '<div class="empty-state"><i class="fas fa-search"></i><p>没有找到匹配的报告</p></div>';
        return;
    }
    
    let html = '';
    
    filteredReports.forEach(report => {
        const statusClass = `status-${report.status}`;
        const statusText = {
            'completed': '已完成',
            'processing': '处理中',
            'failed': '失败'
        }[report.status] || report.status;
        
        html += `
            <div class="report-item" data-id="${report.id}">
                <div class="report-info">
                    <div class="report-title">${report.filename}</div>
                    <div class="report-meta">${report.created_at}</div>
                </div>
                <div class="report-status ${statusClass}">${statusText}</div>
                <div class="report-actions">
                    ${report.status === 'completed' ? `
                        <div class="action-btn view-btn" title="查看报告">
                            <i class="fas fa-eye"></i>
                        </div>
                        <div class="action-btn download-btn" title="下载PDF报告">
                            <i class="fas fa-file-pdf"></i>
                        </div>
                    ` : ''}
                </div>
            </div>
        `;
    });
    
    reportsList.innerHTML = html;
    
    // 添加报告操作事件
    document.querySelectorAll('.view-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const reportId = btn.closest('.report-item').getAttribute('data-id');
            viewReport(reportId);
        });
    });
    
    document.querySelectorAll('.download-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const reportId = btn.closest('.report-item').getAttribute('data-id');
            window.location.href = `/api/reports/${reportId}/download`;
        });
    });
}

async function viewReport(reportId) {
    try {
        const response = await fetch(`/api/reports/${reportId}`);
        const data = await response.json();
        
        if (response.ok && data.status === 'completed') {
            // 切换到分析部分
            navLinks.forEach(l => l.classList.remove('active'));
            sections.forEach(section => {
                if (section.id === 'analysis') {
                    section.classList.add('active');
                    section.style.display = 'block';
                } else {
                    section.classList.remove('active');
                    section.style.display = 'none';
                }
            });
            
            // 更新导航状态
            navLinks.forEach(link => {
                if (link.getAttribute('data-section') === 'analysis') {
                    link.classList.add('active');
                }
            });
            
            // 显示结果
            resultCard.style.display = 'block';
            analysisLoading.style.display = 'none';
            analysisResult.style.display = 'block';
            document.querySelector('.result-actions').style.display = 'flex';
            
            showAnalysisResult(data.result.analysis);
            currentReportId = reportId;
        } else {
            showNotification('无法查看报告，报告可能尚未完成或已失败');
        }
    } catch (error) {
        console.error('查看报告错误:', error);
        showNotification('查看报告时发生错误');
    }
}

// 报告筛选和搜索
reportSearch.addEventListener('input', () => {
    loadReports();
});

reportFilter.addEventListener('change', () => {
    loadReports();
});

// 通知功能
function showNotification(message) {
    notificationMessage.textContent = message;
    notification.classList.add('show');
    
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    // 如果在报告列表页面，加载报告
    if (document.getElementById('reports').style.display !== 'none') {
        loadReports();
    }
});